{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# Install Libs"
      ],
      "metadata": {
        "id": "LpFpdv0HRLQx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install llama-index-tools-finance -q\n",
        "!pip install llama-index -q"
      ],
      "metadata": {
        "id": "Igq8X-1KmFAQ"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "metadata": {
        "id": "6GugUPjbmAKx"
      },
      "outputs": [],
      "source": [
        "from llama_index.tools.finance import FinanceAgentToolSpec"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The whole code in LlamaIndex repo:"
      ],
      "metadata": {
        "id": "kAqbcm7of2HS"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "https://github.com/run-llama/llama_index/tree/main/llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance"
      ],
      "metadata": {
        "id": "LPp7mG1YO76a"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "https://github.com/run-llama/llama_index/blob/main/llama-index-integrations/tools/llama-index-tools-finance/llama_index/tools/finance/base.py"
      ],
      "metadata": {
        "id": "PEDuzzHYpq-J"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "FinanceAgentToolSpec"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 139
        },
        "id": "kmMy7uj6mjyw",
        "outputId": "54205554-f2c8-4477-bf7d-00604af578b3"
      },
      "execution_count": 4,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "llama_index.tools.finance.base.FinanceAgentToolSpec"
            ],
            "text/html": [
              "<div style=\"max-width:800px; border: 1px solid var(--colab-border-color);\"><style>\n",
              "      pre.function-repr-contents {\n",
              "        overflow-x: auto;\n",
              "        padding: 8px 12px;\n",
              "        max-height: 500px;\n",
              "      }\n",
              "\n",
              "      pre.function-repr-contents.function-repr-contents-collapsed {\n",
              "        cursor: pointer;\n",
              "        max-height: 100px;\n",
              "      }\n",
              "    </style>\n",
              "    <pre style=\"white-space: initial; background:\n",
              "         var(--colab-secondary-surface-color); padding: 8px 12px;\n",
              "         border-bottom: 1px solid var(--colab-border-color);\"><b>llama_index.tools.finance.base.FinanceAgentToolSpec</b><br/>def __init__(polygon_api_key: str, finnhub_api_key: str, alpha_vantage_api_key: str, newsapi_api_key: str)</pre><pre class=\"function-repr-contents function-repr-contents-collapsed\" style=\"\"><a class=\"filepath\" style=\"display:none\" href=\"#\">/usr/local/lib/python3.10/dist-packages/llama_index/tools/finance/base.py</a>Base tool spec class.</pre>\n",
              "      <script>\n",
              "      if (google.colab.kernel.accessAllowed && google.colab.files && google.colab.files.view) {\n",
              "        for (const element of document.querySelectorAll('.filepath')) {\n",
              "          element.style.display = 'block'\n",
              "          element.onclick = (event) => {\n",
              "            event.preventDefault();\n",
              "            event.stopPropagation();\n",
              "            google.colab.files.view(element.textContent, 9);\n",
              "          };\n",
              "        }\n",
              "      }\n",
              "      for (const element of document.querySelectorAll('.function-repr-contents')) {\n",
              "        element.onclick = (event) => {\n",
              "          event.preventDefault();\n",
              "          event.stopPropagation();\n",
              "          element.classList.toggle('function-repr-contents-collapsed');\n",
              "        };\n",
              "      }\n",
              "      </script>\n",
              "      </div>"
            ]
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Specify API Keys"
      ],
      "metadata": {
        "id": "UQMDqzFXRHWx"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "POLYGON_API_KEY = userdata.get('POLYGON_API_KEY')\n",
        "FINNHUB_API_KEY = userdata.get('FINNHUB_API_KEY')\n",
        "ALPHA_VANTAGE_API_KEY = userdata.get('ALPHAVANTAGE_API_KEY')\n",
        "NEWS_API_KEY = userdata.get('NEWS_API_KEY')\n",
        "OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')"
      ],
      "metadata": {
        "id": "yUEx3tPwoK5H"
      },
      "execution_count": 6,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Various Pre-Configured Tools"
      ],
      "metadata": {
        "id": "yMhckVtvQ2Ep"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "tool_spec = FinanceAgentToolSpec(\n",
        "        POLYGON_API_KEY,\n",
        "        FINNHUB_API_KEY,\n",
        "        ALPHA_VANTAGE_API_KEY,\n",
        "        NEWS_API_KEY\n",
        "    )"
      ],
      "metadata": {
        "id": "avyOhKXcuhtX"
      },
      "execution_count": 13,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "tool_spec.spec_functions"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8jig1GmFQn6E",
        "outputId": "2566363f-6519-44db-be43-02bfe2807e19"
      },
      "execution_count": 12,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['find_similar_companies',\n",
              " 'get_earnings_history',\n",
              " 'get_stocks_with_upcoming_earnings',\n",
              " 'get_current_gainer_stocks',\n",
              " 'get_current_loser_stocks',\n",
              " 'get_current_undervalued_growth_stocks',\n",
              " 'get_current_technology_growth_stocks',\n",
              " 'get_current_most_traded_stocks',\n",
              " 'get_current_undervalued_large_cap_stocks',\n",
              " 'get_current_aggressive_small_cap_stocks',\n",
              " 'get_trending_finance_news',\n",
              " 'get_google_trending_searches',\n",
              " 'get_google_trends_for_query',\n",
              " 'get_latest_news_for_stock',\n",
              " 'get_current_stock_price_info']"
            ]
          },
          "metadata": {},
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Create an Agent:"
      ],
      "metadata": {
        "id": "jfkPeuiCRWq5"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from llama_index.agent.openai import OpenAIAgent\n",
        "from llama_index.llms.openai import OpenAI"
      ],
      "metadata": {
        "id": "CXJ4qvxPoHqn"
      },
      "execution_count": 15,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "GPT_MODEL_NAME = \"gpt-4o-mini\"\n",
        "\n",
        "def create_agent(\n",
        "    polygon_api_key: str,\n",
        "    finnhub_api_key: str,\n",
        "    alpha_vantage_api_key: str,\n",
        "    newsapi_api_key: str,\n",
        "    openai_api_key: str,\n",
        ") -> OpenAIAgent:\n",
        "    tool_spec = FinanceAgentToolSpec(\n",
        "        polygon_api_key,\n",
        "        finnhub_api_key,\n",
        "        alpha_vantage_api_key,\n",
        "        newsapi_api_key,\n",
        "    )\n",
        "    llm = OpenAI(temperature=0, model=GPT_MODEL_NAME, api_key=openai_api_key)\n",
        "    return OpenAIAgent.from_tools(\n",
        "        tool_spec.to_tool_list(), llm=llm, verbose=True\n",
        "    )\n",
        "\n",
        "agent = create_agent(\n",
        "    POLYGON_API_KEY,\n",
        "    FINNHUB_API_KEY,\n",
        "    ALPHA_VANTAGE_API_KEY,\n",
        "    NEWS_API_KEY,\n",
        "    OPENAI_API_KEY,\n",
        ")"
      ],
      "metadata": {
        "id": "MQiNd_fstK8A"
      },
      "execution_count": 16,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Start Chatting"
      ],
      "metadata": {
        "id": "MSt6fXWHRfsp"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Stock Price"
      ],
      "metadata": {
        "id": "a8dPRQu4XspZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What was the last closing price of amazon?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "CjovtxRERcTJ",
        "outputId": "b770a967-0226-4bd7-feed-fee13a9ad63d"
      },
      "execution_count": 17,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What was the last closing price of amazon?\n",
            "=== Calling Function ===\n",
            "Calling function: get_current_stock_price_info with args: {\"stock_ticker_symbol\":\"AMZN\"}\n",
            "Got output: {'Current Price': 178.5, 'High Price of the day': 178.9, 'Low Price of the day': 172.6, 'Open Price of the day': 172.74, 'Percentage change': 3.7067}\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Amazon latest news: ==>"
      ],
      "metadata": {
        "id": "UEqcacvhXvgp"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "This function \"get_latest_news_for_stock\" returns only NVIDIA news instead of Amazon:"
      ],
      "metadata": {
        "id": "Xs2S8GGGXybb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the latest news about AMZN?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "xv5rKkXTtwV3",
        "outputId": "08414f1d-de2d-4df1-a99a-63cb501ff27b"
      },
      "execution_count": 18,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the latest news about AMZN?\n",
            "=== Calling Function ===\n",
            "Calling function: get_latest_news_for_stock with args: {\"stock_id\":\"AMZN\"}\n",
            "Got output: ['Nvidia stock is sinking. Wall Street analysts say it’s still a buy']\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"I was asking news about Amazon and not NVIDIA.\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jABES6ieuz9R",
        "outputId": "09ec58a3-ba96-4cc3-d241-9bf58ca5d743"
      },
      "execution_count": 25,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: I was asking news about Amazon and not NVIDIA.\n",
            "=== Calling Function ===\n",
            "Calling function: get_latest_news_for_stock with args: {\"stock_id\":\"AMZN\"}\n",
            "Got output: ['Nvidia stock is sinking. Wall Street analysts say it’s still a buy']\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"I was asking news about Amazon and not NVIDIA. What are the latest news about AMZN?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "grrkgEFWu-gY",
        "outputId": "b6658a28-8604-476d-e2d2-d6c41e72f69d"
      },
      "execution_count": 26,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: I was asking news about Amazon and not NVIDIA. What are the latest news about AMZN?\n",
            "=== Calling Function ===\n",
            "Calling function: get_latest_news_for_stock with args: {\"stock_id\":\"AMZN\"}\n",
            "Got output: ['Nvidia stock is sinking. Wall Street analysts say it’s still a buy']\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "To modify it: First you need to dig into the code and understand how it was built:"
      ],
      "metadata": {
        "id": "5brisf0LYPGR"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from newsapi import NewsApiClient\n",
        "from collections import defaultdict"
      ],
      "metadata": {
        "id": "dMZ5heFMS8mZ"
      },
      "execution_count": 29,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "newsapi = NewsApiClient(api_key=NEWS_API_KEY)\n",
        "cat_to_id = defaultdict(list)\n",
        "for source in newsapi.get_sources()[\"sources\"]:\n",
        "    cat_to_id[source[\"category\"]].append(source[\"id\"])\n",
        "business_sources = [\n",
        "        \"bloomberg\",\n",
        "        \"business-insider\",\n",
        "        \"financial-post\",\n",
        "        \"fortune\",\n",
        "        \"info-money\",\n",
        "        \"the-wall-street-journal\",\n",
        "    ]"
      ],
      "metadata": {
        "id": "TfO5IyfNTCZx"
      },
      "execution_count": 30,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "for source in business_sources:\n",
        "  assert source in cat_to_id[\"business\"]\n",
        "cat_to_id[\"business\"]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "zTMv4_x0UOSx",
        "outputId": "81088e0d-1110-4173-ff5f-b3e6426f1675"
      },
      "execution_count": 56,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['argaam',\n",
              " 'australian-financial-review',\n",
              " 'bloomberg',\n",
              " 'business-insider',\n",
              " 'business-insider-uk',\n",
              " 'die-zeit',\n",
              " 'financial-post',\n",
              " 'fortune',\n",
              " 'handelsblatt',\n",
              " 'il-sole-24-ore',\n",
              " 'info-money',\n",
              " 'les-echos',\n",
              " 'the-wall-street-journal',\n",
              " 'wirtschafts-woche']"
            ]
          },
          "metadata": {},
          "execution_count": 56
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "▶ I modified the param \"page\" to \"page_size\" = 3 to get the first 3 articles\n",
        "\n",
        "▶ If you put in the query only \"AMZN\" (ticker) ==> You'll get NVIDIA news\n",
        "\n",
        "▶ If you put Amazon news ==> You'll get Amazon related news"
      ],
      "metadata": {
        "id": "pRXGcjA5Yq3R"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from datetime import datetime, timedelta\n",
        "start_date = (datetime.now() - timedelta(days=7)).strftime(\"%Y-%m-%d\")\n",
        "end_date = datetime.now().strftime(\"%Y-%m-%d\")\n",
        "\n",
        "articles = newsapi.get_everything(\n",
        "        q=\"AMZN\",\n",
        "        sources=\",\".join(business_sources),\n",
        "        from_param=start_date,\n",
        "        to=end_date,\n",
        "        language=\"en\",\n",
        "        sort_by=\"relevancy\",\n",
        "        page_size=3,\n",
        "    )[\"articles\"]\n",
        "articles"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "es2veYLtZ2wh",
        "outputId": "2238ee79-5d19-4290-f8ef-fff2b085443a"
      },
      "execution_count": 57,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[{'source': {'id': 'fortune', 'name': 'Fortune'},\n",
              "  'author': 'Will Daniel',\n",
              "  'title': 'Nvidia stock is sinking. Wall Street analysts say it’s still a buy',\n",
              "  'description': \"Despite concerns about margins and guidance, Wall Street is mostly convinced the 'AI revolution' is just getting started, and Nvidia remains a buy.\",\n",
              "  'url': 'https://fortune.com/2024/08/29/nvidia-stock-sinking-wall-street-analysts-still-buy/',\n",
              "  'urlToImage': 'https://fortune.com/img-assets/wp-content/uploads/2024/08/GettyImages-2155386351-e1724940057818.jpg?resize=1200,600',\n",
              "  'publishedAt': '2024-08-29T18:34:44Z',\n",
              "  'content': 'Nvidia turned in yet another stellar earnings report this week, but with the chip giant priced for perfection amid the AI boom, the stock was still down more than 6% Thursday.\\xa0The risk when a stock i… [+6630 chars]'}]"
            ]
          },
          "metadata": {},
          "execution_count": 57
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "from datetime import datetime, timedelta\n",
        "start_date = (datetime.now() - timedelta(days=7)).strftime(\"%Y-%m-%d\")\n",
        "end_date = datetime.now().strftime(\"%Y-%m-%d\")\n",
        "\n",
        "articles = newsapi.get_everything(\n",
        "        q=\"Amazon news\",\n",
        "        sources=\",\".join(business_sources),\n",
        "        from_param=start_date,\n",
        "        to=end_date,\n",
        "        language=\"en\",\n",
        "        sort_by=\"relevancy\",\n",
        "        page_size=3,\n",
        "    )[\"articles\"]\n",
        "articles"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "THe7lo7WUla5",
        "outputId": "337d0a1b-764b-4a1c-e43f-b57e25764ef7"
      },
      "execution_count": 55,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[{'source': {'id': 'business-insider', 'name': 'Business Insider'},\n",
              "  'author': 'Tom Carter',\n",
              "  'title': 'So, now we know what TV shows Lauren Sánchez and Jeff Bezos binge in their spare time',\n",
              "  'description': \"Lauren Sánchez opened up about her and Jeff Bezos' favorite TV shows in an interview with People magazine.\",\n",
              "  'url': 'https://www.businessinsider.com/jeff-bezos-lauren-sanchez-share-favorite-tv-shows-baby-reindeer-2024-8',\n",
              "  'urlToImage': 'https://i.insider.com/66d19cdd1d8d2deb96b79669?width=1200&format=jpeg',\n",
              "  'publishedAt': '2024-08-30T10:49:06Z',\n",
              "  'content': \"Jeff Bezos and Lauren Sánchez.DREW ANGERER/AFP via Getty Images\\r\\n<ul><li>Lauren Sánchez opened up about her and Jeff Bezos' favorite TV shows in an interview with People magazine.</li><li>Sánchez sai… [+1654 chars]\"},\n",
              " {'source': {'id': 'business-insider', 'name': 'Business Insider'},\n",
              "  'author': 'Dan DeFrancesco',\n",
              "  'title': \"The wealthy's new favorite sport is coming for pickleball's crown\",\n",
              "  'description': 'Padel has gained steam this year as a more active alternative to the widely popular pickleball.',\n",
              "  'url': 'https://www.businessinsider.com/padel-rising-sport-wealthy-pickleball-competitor-2024-8',\n",
              "  'urlToImage': 'https://i.insider.com/66cc7fd71aa2ac29ee340a1b?width=1200&format=jpeg',\n",
              "  'publishedAt': '2024-08-26T13:17:40Z',\n",
              "  'content': \"Jordan Hart/BI\\r\\n<ul><li>This post originally appeared in the Insider Today newsletter.</li><li>You can sign up for Business Insider's daily newsletter here.</li></ul>Welcome back! The summer slowdown… [+8225 chars]\"},\n",
              " {'source': {'id': 'business-insider', 'name': 'Business Insider'},\n",
              "  'author': 'Lindsay Dodgson',\n",
              "  'title': \"MrBeast is in a tough spot. But PR experts say an aggressive 'super lawyer' isn't the fix he needs.\",\n",
              "  'description': \"Crisis management experts say MrBeast going after his critics will only further erode trust with his fans, and he's better off admitting any mistakes.\",\n",
              "  'url': 'https://www.businessinsider.com/mrbeast-jimmy-donaldson-hiring-celebrity-lawyer-wont-help-reputation-experts-2024-8',\n",
              "  'urlToImage': 'https://i.insider.com/66cf0e591aa2ac29ee34e3b4?width=1200&format=jpeg',\n",
              "  'publishedAt': '2024-08-29T13:07:01Z',\n",
              "  'content': 'Jimmy \"MrBeast\" Donaldson has hired a lawyer to fight back against public critics.Don Arnold/Getty Images\\r\\n<ul><li>MrBeast has faced backlash over people in his circle and conditions on his gameshow.… [+7182 chars]'}]"
            ]
          },
          "metadata": {},
          "execution_count": 55
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Trending News"
      ],
      "metadata": {
        "id": "jL6YjIXgawta"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "From seekingalpha"
      ],
      "metadata": {
        "id": "uSG_yDfma3uZ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the top 10 trending news?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "scw9DHmEvK-Q",
        "outputId": "1ca8075a-4daa-4950-a84d-1ab8eb980cb4"
      },
      "execution_count": 62,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the top 10 trending news?\n",
            "=== Calling Function ===\n",
            "Calling function: get_trending_finance_news with args: {}\n",
            "Got output: ['Earnings week ahead: Zscaler, DocuSign, NIO, Broadcom and more', 'Catalyst Watch: August Jobs Report, Intel event, Broadcom earnings, and Costco sales', 'Intel resolves R2 litigation', 'Heavily shorted stocks are not always in distress, S3 Partners analysis says', 'Airlines poised to regain altitude after a tough month', 'Electric vehicle adoption: A disappointment or still on track to reach a critical mass?', 'Netflix works to improve reality-TV dubbing to lure more subscribers', 'Macau casino revenue shines in August; dividends come back into play', 'Notable analyst calls this week: Nvidia, Barrick Gold and Dollar General among top picks', \"CrowdStrike's results prove the worst is behind it. It's time to buy the stock: HSBC\"]\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Eearnings"
      ],
      "metadata": {
        "id": "UdrPezu1bHxD"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "It provides the earning history of a ticker:"
      ],
      "metadata": {
        "id": "5WyJBtLobJfp"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the earnings of AMZN on 2024?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ruIMHYfhwCsI",
        "outputId": "550b990f-5de7-4a67-8433-201cb2187c9e"
      },
      "execution_count": 31,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the earnings of AMZN on 2024?\n",
            "=== Calling Function ===\n",
            "Calling function: get_earnings_history with args: {\"symbol\": \"AMZN\"}\n",
            "Got output:     Fiscal Date Ending Reported Date Reported EPS Estimated EPS Surprise  \\\n",
            "0           2024-06-30    2024-08-01         1.26          1.03     0.23   \n",
            "1           2024-03-31    2024-04-30         0.98          0.82     0.16   \n",
            "2           2023-12-31    2024-02-01            1           0.8      0.2   \n",
            "3           2023-09-30    2023-10-26         0.94          0.58     0.36   \n",
            "4           2023-06-30    2023-08-03         0.65          0.35      0.3   \n",
            "..                 ...           ...          ...           ...      ...   \n",
            "104         1998-06-30    1998-07-22        -0.07         -0.07        0   \n",
            "105         1998-03-31    1998-04-27        -0.03         -0.04     0.01   \n",
            "106         1997-12-31    1998-01-22        -0.03         -0.04     0.01   \n",
            "107         1997-09-30    1997-10-27        -0.03         -0.03        0   \n",
            "108         1997-06-30    1997-07-10        -0.02         -0.03     0.01   \n",
            "\n",
            "    Surprise Percentage  \n",
            "0               22.3301  \n",
            "1               19.5122  \n",
            "2                    25  \n",
            "3                62.069  \n",
            "4               85.7143  \n",
            "..                  ...  \n",
            "104                   0  \n",
            "105                  25  \n",
            "106                  25  \n",
            "107                   0  \n",
            "108             33.3333  \n",
            "\n",
            "[109 rows x 6 columns]\n",
            "========================\n",
            "\n",
            "=== Calling Function ===\n",
            "Calling function: get_earnings_history with args: {\"symbol\": \"AMZN\"}\n",
            "Got output:     Fiscal Date Ending Reported Date Reported EPS Estimated EPS Surprise  \\\n",
            "0           2024-06-30    2024-08-01         1.26          1.03     0.23   \n",
            "1           2024-03-31    2024-04-30         0.98          0.82     0.16   \n",
            "2           2023-12-31    2024-02-01            1           0.8      0.2   \n",
            "3           2023-09-30    2023-10-26         0.94          0.58     0.36   \n",
            "4           2023-06-30    2023-08-03         0.65          0.35      0.3   \n",
            "..                 ...           ...          ...           ...      ...   \n",
            "104         1998-06-30    1998-07-22        -0.07         -0.07        0   \n",
            "105         1998-03-31    1998-04-27        -0.03         -0.04     0.01   \n",
            "106         1997-12-31    1998-01-22        -0.03         -0.04     0.01   \n",
            "107         1997-09-30    1997-10-27        -0.03         -0.03        0   \n",
            "108         1997-06-30    1997-07-10        -0.02         -0.03     0.01   \n",
            "\n",
            "    Surprise Percentage  \n",
            "0               22.3301  \n",
            "1               19.5122  \n",
            "2                    25  \n",
            "3                62.069  \n",
            "4               85.7143  \n",
            "..                  ...  \n",
            "104                   0  \n",
            "105                  25  \n",
            "106                  25  \n",
            "107                   0  \n",
            "108             33.3333  \n",
            "\n",
            "[109 rows x 6 columns]\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "It didn't succeed to call the estimated ones \"get_latest_earning_estimate\""
      ],
      "metadata": {
        "id": "gGiVonV0euR6"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the latest actual and estimated earning of AMZN?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "a65lFT-iwgYA",
        "outputId": "894acc87-9ea4-4e37-a4b9-87043577f5a3"
      },
      "execution_count": 67,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the latest actual and estimated earning of AMZN?\n",
            "=== Calling Function ===\n",
            "Calling function: get_earnings_history with args: {\"symbol\":\"AMZN\"}\n",
            "Got output:     Fiscal Date Ending Reported Date Reported EPS Estimated EPS Surprise  \\\n",
            "0           2024-06-30    2024-08-01         1.26          1.03     0.23   \n",
            "1           2024-03-31    2024-04-30         0.98          0.82     0.16   \n",
            "2           2023-12-31    2024-02-01            1           0.8      0.2   \n",
            "3           2023-09-30    2023-10-26         0.94          0.58     0.36   \n",
            "4           2023-06-30    2023-08-03         0.65          0.35      0.3   \n",
            "..                 ...           ...          ...           ...      ...   \n",
            "104         1998-06-30    1998-07-22        -0.07         -0.07        0   \n",
            "105         1998-03-31    1998-04-27        -0.03         -0.04     0.01   \n",
            "106         1997-12-31    1998-01-22        -0.03         -0.04     0.01   \n",
            "107         1997-09-30    1997-10-27        -0.03         -0.03        0   \n",
            "108         1997-06-30    1997-07-10        -0.02         -0.03     0.01   \n",
            "\n",
            "    Surprise Percentage  \n",
            "0               22.3301  \n",
            "1               19.5122  \n",
            "2                    25  \n",
            "3                62.069  \n",
            "4               85.7143  \n",
            "..                  ...  \n",
            "104                   0  \n",
            "105                  25  \n",
            "106                  25  \n",
            "107                   0  \n",
            "108             33.3333  \n",
            "\n",
            "[109 rows x 6 columns]\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Similar companies"
      ],
      "metadata": {
        "id": "TjZgiWtJe0PK"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the similar companies of AMZN?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "rebECQBny-T5",
        "outputId": "3b2a7505-f28c-4abd-c5ac-99e419a33af7"
      },
      "execution_count": 34,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the similar companies of AMZN?\n",
            "=== Calling Function ===\n",
            "Calling function: find_similar_companies with args: {\"symbol\":\"AMZN\"}\n",
            "Got output: ['AMZN', 'CPNG', 'EBAY', 'ETSY', 'DDS', 'OLLI', 'M', 'JWN', 'KSS', 'SVV']\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Growth Stocks"
      ],
      "metadata": {
        "id": "L4CZiNIve9l6"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "\"get_current_technology_growth_stocks\" didn't succed to get data ==> one needs to modify it ...It uses yfinance url"
      ],
      "metadata": {
        "id": "q3udCsTne_ox"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the growth stocks in technology sector in US market?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "58GofB1SzZqp",
        "outputId": "77b7c915-4abe-447a-a973-bd4d6b53aea7"
      },
      "execution_count": 69,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the growth stocks in technology sector in US market?\n",
            "=== Calling Function ===\n",
            "Calling function: get_current_technology_growth_stocks with args: {}\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/llama_index/tools/finance/util.py:29: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object.\n",
            "  return pd.read_html(html_clean, header=header)\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Got output:                                                    0\n",
            "0  Will be right back...  Thank you for your pati...\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "response = agent.chat(\"What are the US stocks gainers?\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "SxXV1ogE17eq",
        "outputId": "2b0f0b0a-8d4f-45b6-9df9-0395cf15606b"
      },
      "execution_count": 55,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Added user message to memory: What are the US stocks gainers?\n",
            "=== Calling Function ===\n",
            "Calling function: get_current_gainer_stocks with args: {}\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stderr",
          "text": [
            "/usr/local/lib/python3.10/dist-packages/llama_index/tools/finance/util.py:29: FutureWarning: Passing literal html to 'read_html' is deprecated and will be removed in a future version. To read from a literal string, wrap it in a 'StringIO' object.\n",
            "  return pd.read_html(html_clean, header=header)\n"
          ]
        },
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Got output:                                                    0\n",
            "0  Will be right back...  Thank you for your pati...\n",
            "========================\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Key Takeways"
      ],
      "metadata": {
        "id": "JohdRSpsfN3I"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "◾ Overall, this agent is a good starting point if you want to build one.\n",
        "\n",
        "◾ You can draw inspiration from the work done here to improve and customize it for your own use case.\n",
        "\n",
        "◾ You can also use another LLM as AI Agent like Claude 3.5 Sonnet."
      ],
      "metadata": {
        "id": "xisBItEdfP7R"
      }
    }
  ]
}